﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;

using Argotic.Syndication;

using LightReader.Business.Services.Contracts;
using LightReader.Business.Entities;
using Argotic.Common;

namespace LightReader.Business.Services
{
    public class LightReaderService : ILightReaderService
    {
        #region ILightReaderService Members
        // TODO: Need a way to validate that a feed is good.       
        public Feed GetFeed(string feedUrl)
        {
            Feed returnVal = null;
            if (feedUrl.Length > 0)
            {
                GenericSyndicationFeed originalFeed = GenericSyndicationFeed.Create(new Uri(feedUrl));
                SyndicationContentFormat format = originalFeed.Format;
                // handle RSS and Atom
                if (originalFeed.Format == Argotic.Common.SyndicationContentFormat.Rss)
                {
                    RssFeed feed = originalFeed.Resource as RssFeed;
                    if (feed != null)
                    {
                        returnVal = new Feed();
                        returnVal.Name = feed.Channel.Title;
                        returnVal.Publisher = feed.Channel.ManagingEditor;
                        returnVal.Description = feed.Channel.Description;
                        returnVal.Url = feed.Channel.Link;
                        if (feed.Channel.Items != null)
                        {
                            returnVal.Items = new List<Post>();
                            foreach (RssItem ri in feed.Channel.Items)
                            {
                                Post p = new Post();
                                p.Name = ri.Title;
                                p.Guid = ri.Guid.Value;
                                p.PublishDate = ri.PublicationDate;
                                p.Url = ri.Link;
                                p.Content = Convert(ri.Description);

                                returnVal.Items.Add(p);
                            }
                        }
                    }
                }
                else if (originalFeed.Format == Argotic.Common.SyndicationContentFormat.Atom)
                {
                    AtomFeed feed = originalFeed.Resource as AtomFeed;
                    returnVal = new Feed();
                    returnVal.Name = feed.Title.Content;
                    returnVal.Description = string.Empty;
                    string author = string.Empty;
                    if (feed.Authors.Count > 0)
                    {
                        author = feed.Authors[0].Name;
                    }
                    returnVal.Publisher = author;
                    returnVal.Url = feed.Links[0].Uri;
                    if (feed.Entries != null)
                    {
                        returnVal.Items = new List<Post>();
                        foreach (AtomEntry ri in feed.Entries)
                        {
                            Post p = new Post();
                            p.Name = ri.Title.Content;
                            p.PublishDate = ri.PublishedOn;
                            p.Guid = ri.Id.ToString();
                            p.Url = ri.Links[0].Uri;

                            string content = string.Empty;
                            if (ri.Content == null)
                            {
                                content = ri.Summary.Content;
                            }
                            else 
                            {
                                content = ri.Content.Content;
                            }
                            p.Content = content;

                            returnVal.Items.Add(p);
                        }
                    }

                }
            }
            return returnVal;
        }

        public List<Feed> ImportOPML(string opmlContents)
        {
            List<Feed> returnVal = null;

            XmlReaderSettings xrs = new XmlReaderSettings();
            xrs.MaxCharactersInDocument = 0;
            OpmlDocument opml = new OpmlDocument();
            opml.Load(XmlReader.Create(new StringReader(opmlContents), xrs));

            if (opml.Outlines != null)
            {
                returnVal = new List<Feed>();
                string folderName = string.Empty;
                foreach (OpmlOutline ol in opml.Outlines)
                {
                    if (ol.Outlines.Count > 0)
                    {
                        foreach (OpmlOutline ol2 in ol.Outlines)
                        {
                            if (ol2.IsSubscriptionListOutline)
                            {
                                Feed newFeed = new Feed();
                                string feedName = ol2.Attributes["title"];
                                newFeed.Name = feedName;
                                newFeed.Url = new Uri(ol2.Attributes["xmlUrl"]);

                                returnVal.Add(newFeed);
                            }
                        }
                    }
                    if (ol.IsSubscriptionListOutline)
                    {
                        Feed newFeed = new Feed();
                        string feedName = ol.Attributes["title"];
                        newFeed.Name = feedName;
                        newFeed.Url = new Uri(ol.Attributes["xmlUrl"]);

                        returnVal.Add(newFeed);
                    }
                }
            }
            return returnVal;
        }
        #endregion

        // snagged from the RSS reader sample found 
        // here: http://code.msdn.microsoft.com/silverlightws/Release/ProjectReleases.aspx?ReleaseId=601
        // slightly modified by Michael Eaton on 3/15/2008.
        private string Convert(string value)
        {
            //// Remove HTML tags and empty newlines and spaces
            //string temp = HttpUtility.HtmlDecode(value);
            //temp = Regex.Replace(temp, "</p>", "\n\n");
            //string returnString = temp; // Regex.Replace(temp, "<.*?>", "");
            //returnString = Regex.Replace(returnString, @"\n+\s+", "\n\n");

            //// Decode HTML entities
            //returnString = HttpUtility.HtmlDecode(returnString);

            //return returnString;
            return value;
        }
    }
}
